"use strict";
import api from '../../api';
import axios from "axios";

// 请勿删除下面这个对象
const arr = {
  'advice': 0, 'doneadvice': 1, 'doingadvice': 2, 'okadvice': 3, 'notadvice': 4,
  'need': 0, 'doneneed': 1, 'doingneed': 2, 'okneed': 3, 'notneed': 4,
};

export default {
  state: {
    pid: null,


    advice: [],// 用户建议（还未处理）
    doneadvice: [],// 已完成建议
    doingadvice: [],// 近期执行（已采纳）
    okadvice: [],// 已采纳
    notadvice: [],// 未采纳（不考虑）

    need: [],
    doneneed: [],
    doingneed: [],
    okneed: [],
    notneed: [],
  },
  mutations: {
    /**
     * 添加用户建议或需求
     * @param state 传入一个数组
     * @param payload
     */
    addAdviceOrNeed(state, payload) {
      if (Object.prototype.toString.call(payload) !== '[object Array]') {
        console.log('请传入一个数组');
        return;
      }
      for (let item of payload) {
        //只装载state = [suggest,demand]类型的数据
        var p={'suggest':'','demand':''};
        if(!p.hasOwnProperty(item["state"])){
          continue;
        }
        let type = item["state"] === 'suggest' ? 'advice' : 'need';
        let tagvalue;
        for (let tag of item.tags) {
          if (tag.key === 'suggest' || tag.key === 'demand') {
            tagvalue = tag.value;
          } else {
            item[tag.key] = tag.value;
          }
        }
        let temps = item.desc.split('--联系方式：');
        let desc = temps[0];
        item.origDesc = temps[0];
        if (temps.length > 1) {
          //表示有联系方式
          desc += '--联系方式：' + addXing(temps[1], 3, 4);
          if(!item.phoneNum)item.phoneNum = temps[1];
        }
        item.desc = desc;
        //
        state[tagvalue + type].push(item);
      }
      console.log('state');
      console.log(state);
      return ;
    },
    delAdviceOrNeed(state, payload){

      let keys = Object.keys(arr);
      for(var j=0; j<keys.length; j++){
        let key = keys[j];
        for(var i=0; i<state[key].length; i++){
          if(state[key][i].id == payload.id){
            console.log(state[key][i].id, payload.id, state[key]);
            state[key].splice(i, 1);
            return;
          }
        }
      }
    },
    updateAdviceOrNeed(state, payload){
      console.log(state);
      Object.keys(arr).forEach(key=>{
        state[key].forEach(item=>{
          if(item.id == payload[0].id){
            Object.keys(payload[0]).forEach(k=>{
              item[k] = payload[0][k];
            });
          }
        });
      });
    },
    /**
     * 清空指定数据
     * @param state
     * @param stat
     */
    empty(state , stat = 'need'){
      let keys = Object.keys(arr);
      if(stat == 'need'){
        keys = keys.slice(5,10);
      }else{
        keys = keys.slice(0,6);
      }
      keys.forEach(key=>{
        state[key] = [];
      });
    },
    /**
     * 设置pid
     * @param state
     * @param payload
     */
    setPid(state, payload) {
      state.pid = payload;
    },
    /**
     * 排序
     * @param state
     * @param payload
     */
    sort(state, payload) {
      for (let name in arr) {
        let sort = localStorage.getItem(name + 'sort');
        sort = sort ? sort.substring(0, sort.length - 1).split(',') : [];
        //给数组生成一种方便取出的格式
        let sdata = {};
        state[name].forEach(item => {
          sdata[item.id] = item;
        });
        let list = [];
        for (let taskid of sort) {
          let item = sdata[taskid];
          if (item) {
            list.push(sdata[taskid]);
            delete sdata[taskid];
          }
        }
        let tmpList = [];
        for (let taskid in sdata) {
          tmpList.push(sdata[taskid]);
        }

        tmpList.sort((task1, task2) => {
          return (task2.like - task2.unlike) - (task1.like - task1.unlike);
        });
        state[name] = [...list, ...tmpList];
      }
    },
    /**
     *移动task
     * @param state
     * @param payload
     */
    moveTask(state, payload) {
      //找到task
      let type = payload.key === 'suggest' ? 'advice' : 'need';
      let tasks = state[payload.fromKey + type];
      tasks.forEach((item, index) => {
        if (parseInt(item.id) === parseInt(payload.id)) {
          for (let tag of item.tags) {
            if (tag.key === payload.key) {
              //修改
              tag.value = payload.toKey;
              //push
              state[payload.toKey + type].push(item);
              break;
            }
          }
          //删除元素
          state[payload.fromKey + type].splice(index, 1);
          return
        }
      });
      console.log('把' + payload.id + '从', payload.fromKey, '移动到', payload.toKey);
    },
    likeOrUnlike(state, payload) {
      state[payload.taskType].forEach((item) => {
        if (parseInt(item.id) === parseInt(payload.taskid)) {
          item[payload.key]++;
          item.tags.forEach(tag => {
            if (tag.key == payload.key) {
              tag.value++;
              return;
            }
          })
          return;
        }
      });
      console.log('给', payload.taskid, payload.key)
    },
  },
  actions: {
    /**
     * 添加用户建议或需求
     * @param ctx
     * @param data 传入一个对象
     * @returns {Promise<string>}
     */
    async addAdviceOrNeed(ctx, data) {
      try {
        //检查参数
        if (!data.title) return '请输入标题';
        //处理电话号码
        let phoneNum = '';
        if (data.phoneNum) {
          //判断电话号码是否正确
          phoneNum = '--联系方式：' + data.phoneNum;
        }
        let sdata = {
          title: data.title,
          desc: data.desc + phoneNum,
          state: data.state,
          pid: ctx.state.pid,
          tags: {like: 0, unlike: 0},
        };
        sdata.tags[data["state"]] = "";
        let result = await api.taskAdd(sdata);
        if (result.errno === 0) {
          ctx.commit('addAdviceOrNeed', [result.data]);
          return;
        } else {
          return result.errmsg;
        }
      } catch (err) {
        return err.message;
      }
    },
    /**
     * 查询用户建议或需求
     * @param ctx
     * @param data
     * @returns {Promise<void>}
     */
    async queryAdviceOrNeed(ctx, data) {
      try {
        let result = await api.tasksGet({...data, pid: ctx.state.pid});
        if (result.errno === 0) {
          ctx.commit('addAdviceOrNeed', result.data.tasks);
          ctx.commit('sort');//排序
        } else {
          console.log(result.errmsg);
        }
      } catch (err) {
        return err.message;
      }
    },
    /**
     * 修改用户建议或需求状态（标签）
     * @param ctx
     * @param data
     * @returns {Promise<void>}
     */
    async updateAdviceOrNeedTag(ctx, data) {
      try {
        let sendData = {
          value: data.toKey,//需要修改的值
          taskid: data.id,
          pid: null,
          //下面与标签相关
          id: '',//需要修改的标签id
          bid: '',
        };

        //从原来的数组中取到task，并删除它
        let type = data.key === 'suggest' ? 'advice' : 'need';
        let tasks = ctx.state[data.fromKey + type];
        tasks.forEach((item, index) => {
          if (parseInt(item.id) === parseInt(data.id)) {
            sendData.pid = item.pid;
            for (let tag of item.tags) {
              if (tag.key === data.key) {
                sendData.id = tag.id;
                sendData.bid = tag.bid;
                break;
              }
            }
            return;
          }
        });

        let result = await api.tagSet(sendData);
        if (result.errno === 0) {
          ctx.commit('moveTask', data);//移动task
          ctx.commit('sort');//排序
          return;
        }
        return result.errmsg;
      } catch
        (err) {
        return err.message;
      }
    },
    /**
     * 赞或踩
     * @param ctx
     * @param data
     * @returns {Promise<*>}
     */
    async likeOrUnlike(ctx, data) {
      try {
          let result = await api.Likeset({...data});
          if (result.errno === 0) {
            //进行相应的赞或踩
            ctx.commit('likeOrUnlike', data);
            ctx.commit('sort');//排序
            return;
          } else {
            return result.errmsg;
          }
      } catch
        (err) {
        return err.message;
      }
    },

    /**
     * 修改用户建议或需求
     * @param ctx
     * @param data 传入一个对象
     * @returns {Promise<string>}
     */
    async updateAdviceOrNeed(ctx, data) {
      try {
        //检查参数
        if (!data.title) return '请输入标题';
        //处理电话号码
        let phoneNum = '';
        if (data.phoneNum) {
          //判断电话号码是否正确
          phoneNum = '--联系方式：' + data.phoneNum;
        }
        let sdata = {
          title: data.title,
          desc: data.desc + phoneNum,
          id: data.id
        };
        
        let result = await api.taskSet(sdata);
        if (result.errno === 0) {
          sdata.origDesc = data.desc;
          sdata.phoneNum = data.phoneNum;
          sdata.desc = data.desc ;
          if(data.phoneNum) sdata.desc+= '--联系方式：' + addXing(data.phoneNum, 3, 4);
        
          ctx.commit('updateAdviceOrNeed', [sdata]);
          ctx.commit('sort');//排序
          return false;
        } else {
          return result.errmsg;
        }
      } catch (err) {
        return err.message;
      }
    },
    /**
     * 删除用户建议或需求
     * @param ctx
     * @param data 传入一个对象
     * @returns {Promise<string>}
     */
    async delAdviceOrNeed(ctx, data){
      try {
        let sdata = {
          id: data.id,
          suggest:1
        };
        
        let result = await api.taskDel(sdata);
        if (result.errno === 0) {
          ctx.commit('delAdviceOrNeed', sdata);
          ctx.commit('sort');//排序
          return false;
        } else {
          return result.errmsg;
        }
      } catch (err) {
        console.log(err.message);
        return err.message;
      }
    }
    //下面是action结束
  },
}

/**
 * 添加星号（*）
 * @param str
 * @param startLen
 * @param endLen
 * @returns {string}
 */
function addXing(str, startLen, endLen) {
  let len = str.length - startLen - endLen;
  let xing = '';
  for (var i = 0; i < len; i++) {
    xing += '*';
  }
  return str.substr(0, startLen) + xing + str.substr(str.length - endLen);
}
